<template>
  <div class="app-store-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索应用..."
        class="search-input"
        :prefix-icon="Search"
        clearable
        @input="handleSearch"
      >
        <template #append>
          <el-button :icon="Search">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 分类标签 -->
    <div class="category-section">
      <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
        <el-tab-pane label="全部应用" name="all" />
        <el-tab-pane label="AI助手" name="ai" />
        <el-tab-pane label="数据分析" name="data" />
        <el-tab-pane label="开发工具" name="dev" />
        <el-tab-pane label="自动化" name="automation" />
      </el-tabs>

      <!-- 标签筛选 -->
      <div class="tags-filter">
        <el-tag
          v-for="tag in tags"
          :key="tag.value"
          :type="activeTag === tag.value ? '' : 'info'"
          class="tag-item"
          @click="handleTagClick(tag.value)"
          :effect="activeTag === tag.value ? 'dark' : 'plain'"
        >
          {{ tag.label }}
        </el-tag>
      </div>
    </div>

    <!-- 应用列表 -->
    <div class="apps-grid" v-loading="loading">
      <el-empty v-if="!loading && filteredApps && filteredApps.length === 0" description="没有找到相关应用" />
      <el-row :gutter="20" v-else>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="app in filteredApps" :key="app.id">
          <el-card shadow="hover" class="app-card">
            <div class="app-icon">
              <el-image :src="app.icon" fit="cover" />
            </div>
            <div class="app-info">
              <h3 class="app-name">{{ app.name }}</h3>
              <p class="app-description">{{ app.description }}</p>
              <div class="app-meta">
                <el-rate v-model="app.rating" disabled text-color="#ff9900" />
                <span class="downloads">{{ app.downloads }}次下载</span>
              </div>
              <div class="app-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  :loading="app.installing"
                  @click="handleInstall(app)"
                >
                  {{ app.installed ? '已安装' : '安装' }}
                </el-button>
                <el-button 
                  type="text" 
                  size="small"
                  @click="showAppDetail(app)"
                >
                  详情
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore">
      <el-button :loading="loading" @click="loadMore">加载更多</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getAppStoreList } from '../../api/app'

const searchQuery = ref('')
const activeCategory = ref('all')
const activeTag = ref('')
const apps = ref([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)

// 标签列表
const tags = [
  { label: '全部', value: '' },
  { label: '免费', value: 'free' },
  { label: '付费', value: 'paid' },
  { label: '热门', value: 'hot' },
  { label: '新品', value: 'new' }
]

// 计算属性：过滤后的应用列表
const filteredApps = computed(() => {
  return apps.value.filter(app => {
    // 搜索过滤
    if (searchQuery.value && !app.name.toLowerCase().includes(searchQuery.value.toLowerCase())) {
      return false
    }
    // 分类过滤
    if (activeCategory.value !== 'all' && app.category !== activeCategory.value) {
      return false
    }
    // 标签过滤
    if (activeTag.value === 'free' && app.price > 0) {
      return false
    }
    if (activeTag.value === 'paid' && app.price === 0) {
      return false
    }
    return true
  })
})

// 加载应用列表
const loadAppList = async () => {
  try {
    loading.value = true
    const response = await getAppStoreList()
    console.log(response)
    apps.value = response || []
  } catch (error) {
    console.error('Failed to load app list:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  // 实际项目中这里会调用API
  console.log('Searching for:', searchQuery.value)
}

// 处理分类切换
const handleCategoryChange = (tab) => {
  console.log('Category changed to:', tab.props.name)
  activeCategory.value = tab.props.name
}

// 处理标签点击
const handleTagClick = (tag) => {
  activeTag.value = activeTag.value === tag ? '' : tag
}

// 处理应用安装
const handleInstall = (app) => {
  if (app.installed) {
    ElMessage.success(`正在打开 ${app.name}`)
  } else {
    ElMessage.success(`正在安装 ${app.name}`)
    // 这里添加实际的安装逻辑
  }
}

// 显示应用详情
const showAppDetail = (app) => {
  ElMessage.info(`查看 ${app.name} 的详细信息`)
  // 这里可以打开详情弹窗或跳转到详情页
}

// 加载更多
const loadMore = async () => {
  if (!hasMore.value || loading.value) return
  loading.value = true
  // 模拟加载
  await new Promise(resolve => setTimeout(resolve, 1000))
  loading.value = false
  page.value++
  if (page.value >= 3) {
    hasMore.value = false
  }
}

onMounted(() => {
  loadAppList()
})
</script>

<style scoped>
.app-store-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.search-input {
  max-width: 600px;
}

.category-section {
  margin-bottom: 30px;
}

.tags-filter {
  margin-top: 20px;
}

.tag-item {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.tag-item:hover {
  opacity: 0.8;
}

.apps-grid {
  margin-bottom: 30px;
}

.app-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.app-card:hover {
  transform: translateY(-5px);
}

.app-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  border-radius: 16px;
  overflow: hidden;
}

.app-info {
  text-align: center;
}

.app-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 600;
}

.app-description {
  margin: 0 0 10px;
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-meta {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  gap: 10px;
}

.downloads {
  font-size: 12px;
  color: #999;
}

.app-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

:deep(.el-tabs__nav) {
  margin-bottom: 10px;
}
</style>
